package com.zztl.infiniteBand.util

import java.math.RoundingMode
import java.text.DecimalFormat

/**
 * @desc
 * @auth ${user}
 * @time 2018/9/11  18:01
 */
object DataFormatUtil {




    fun toHexInt(num: Int): Int {
        return if (num >= 0) num else num + 256
    }

    //将list转换为带有 ， 的字符串
    fun listToString(list: List<String>?): String {
        val sb = StringBuilder()
        if (list != null && list.size > 0) {
            for (i in list.indices) {
                if (i < list.size - 1) {
                    sb.append(list[i] + ",")
                } else {
                    sb.append(list[i])
                }
            }
        }
        return sb.toString()
    }

    //16进制转ascii码
    fun convertHexToAscii(hex: String): String {
        val sb = StringBuilder()
        val temp = StringBuilder()      //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        var i = 0
        while (i < hex.length - 1) {          //grab the hex in pairs
            val output = hex.substring(i, i + 2)          //convert hex to decimal
            val decimal = Integer.parseInt(output, 16)          //convert the decimal to character
            sb.append(decimal.toChar())
            temp.append(decimal)
            i += 2
        }
        return sb.toString()
    }

    /**
     * 保留4位小数点
     *
     * @return
     */
    fun converTxtPoint4(number: Double): String {
        val decimalFormat = DecimalFormat("#.0000")
        if (number == 0.0) {
            return "0.00"
        }
        var format = decimalFormat.format(number)
        if (format.startsWith(".")) {
            format = "0$format"
        }
        if (format.startsWith("-") && format[1] == '.') {
            format = "-0" + format.substring(1, format.length)
        }
        for (i in format.length - 1 downTo 0) {
            if (format[i] != '0') {
                format = format.substring(0, i + 1)
                if (format.endsWith(".")) {
                    format = format.substring(0, format.length - 1)
                }
                return format
            }
        }
        /*while (format.endsWith("0")) {
            format = format.substring(0, format.length());
        }*/
        return format
    }


    /**
     * 保留2位小数点
     *
     * @return
     */
    fun converTxtPoint2(number: String): String {
      if(number.contains(".")&&number.length-number.indexOf(".")>3){
          return number.substring(0,number.indexOf(".")+3)
      }
        return number
    }


    fun getFormat(length: Int, value: Float): String {

        val df = DecimalFormat()
        df.maximumFractionDigits = length
        df.groupingSize = 0
        df.roundingMode = RoundingMode.FLOOR
        return df.format(value.toDouble())

    }
}
